<?php

namespace app\index\service\wrappers;

use app\common\model\ConsultingMessage;
use app\index\dao\ConsultingServerDao;

/**
 *
 * Class ServerMessageWrapper
 * @package app\consulting\service\wrappers
 */
class ServerMessageWrapper implements MessageWrapperInterface
{
    private ConsultingServerDao $consultingServerDao;

    public function __construct(ConsultingServerDao $consultingServerDao)
    {
        $this->consultingServerDao = $consultingServerDao;
    }

    /**
     * 包装动态消息
     * @param ConsultingMessage $message
     * @return void
     */
    public function wrapMessage(ConsultingMessage $message)
    {
        // 查询并获取 server 内容
        $content = $message->content;
        $id = $content->id ?? null;
        if (is_id($id)) {
            $server = $this->consultingServerDao->findCardMessage($id);
            if ($server) {
                $content = object_merge($content, $server->toArray());
                $message->set('content', $content);
            }
        }
    }

    /**
     * 批量包装动态消息
     * @param array $messages
     * @return void
     */
    public function wrapMessages(array $messages)
    {
        $ids = [];
        foreach ($messages as $message) {
            $content = $message->content;
            $id = $content->id ?? null;
            if (is_id($id)) {
                $ids[] = $id;
            }
        }

        $ids = array_values(array_unique($ids));

        if (!empty($ids)) {
            $servers = $this->consultingServerDao->selectCardMessage($ids)->column(null, 'id');
            foreach ($messages as $message){
                $content = $message->content;
                $id = $content->id ?? null;
                $server = $servers[$id] ?? null;
                if ($server) {
                    $content = object_merge($content, $server->toArray());
                    $message->set('content', $content);
                }
            }
        }
    }
}
